<?php

namespace App\Services;

use Illuminate\Database\Eloquent\Builder;

class QueryService
{
    /**
     * 封装条件查询
     *
     * @param Builder $query
     * @param array $conditions
     * @return Builder
     */
    public static function applyConditions(Builder $query, array $conditions)
    {
        foreach ($conditions as $field => $value) {
            if ($value!== null) {
                if (is_array($value)) {
                    if (count($value) === 2 && isset($value[0], $value[1])) {
                        // 范围查询
                        $query->whereBetween($field, $value);
                    } else {
                        // IN 查询
                        $query->whereIn($field, $value);
                    }
                } elseif (str_contains($value, '%')) {
                    // 模糊查询
                    $query->where($field, 'like', $value);
                } else {
                    // 普通等值查询
                    $query->where($field, $value);
                }
            }
        }
        return $query;
    }
}
